import { $event } from '/utils'
import { GlobalData } from '/store/state'
import { topicApi } from '/api/topic'
import { getServer } from '/store/mutations'

Page({
  data: {
    navigationHeight: GlobalData.navigationHeight,
    access: GlobalData.access,
    currencyName: GlobalData.currencyName,
    noMore: false,
    currentTab: 0 /**分类下标 */,
    navScrollLeft: 0,
    /** 最热*/
    list: [] as any[],
    navData: [{ id: 0, name: '推荐', isLastPage: false }] as any[],
    currentTabList: [] as number[],
    /** 最新 */
    list1: [] as any[],
    navData1: [{ id: 0, name: '推荐', isLastPage: false }] as any[],
    currentTabList1: [] as number[],
    cur: 0 /**最新，最热下标 */,
    user: {} as DomoUser,
    canCreate: false,
    create_permission: '',
    paytoast: false,
    chooseTopic: {} as DomoTopic,
    visible: false,
    hidden: false,
  },
  async onLoad() {
    const navData = await topicApi.getTopicClassify()
    this.setData({
      navigationHeight: GlobalData.navigationHeight,
      access: GlobalData.access,
      currencyName: GlobalData.currencyName,
      navData: [...this.data.navData, ...navData.data],
      navData1: [...this.data.navData1, ...navData.data],
    })
    await this.onReset()
    this.getUserInfo()
    this.resolveCreateTopic()
  },
  onShow() {
    $event.on('after:boot', this, () => {
      this.getPostition()
    })
    $event.on('after:joinTopic', this, (topic: DomoTopic) => {
      this.changeTopic(topic)
    })
    $event.on('after:deleteTopic', this, (topic: DomoTopic) => {
      this.deleteTopic(topic)
    })
    $event.on('erorr:integral', this, ({ paytoast, topic }) => {
      this.setData({
        paytoast,
        chooseTopic: topic,
      })
    })
    this.getPostition()
  },
  getPostition() {
    this.setData!({
      navigationHeight: GlobalData.navigationHeight,
      access: GlobalData.access,
      currencyName: GlobalData.currencyName,
    })
  },
  /** 获取用户信息 */
  getUserInfo() {
    const server = getServer()
    const user = wx.getStorageSync(`${server}/logged`).data
    this.setData({
      user,
    })
  },
  clickTab(e: any) {
    if (this.data.cur === +e.target.dataset.current) {
      return
    } else {
      this.setData({
        cur: +e.target.dataset.current,
      })
    }
    //没有有缓存，切换Tab请求数据
    if (
      (this.data.cur === 0 && this.data.currentTabList.indexOf(this.data.currentTab) === -1) ||
      (this.data.cur === 1 && this.data.currentTabList1.indexOf(this.data.currentTab) === -1)
    ) {
      this.onReset()
    }
  },
  switchNav(event: WechatMiniprogram.CustomEvent) {
    const windowWidth = GlobalData.clientWidth
    const cur = event.currentTarget.dataset.current
    //每个tab选项宽度占1/5
    const singleNavWidth = windowWidth / 5
    //tab选项居中
    this.setData({
      navScrollLeft: (cur - 2) * singleNavWidth,
    })
    if (this.data.currentTab == cur) {
      return
    } else {
      this.setData({
        currentTab: cur,
      })
      this.switchList()
    }
  },
  switchList() {
    //tab选中的改变和siwper滑动改变的方法写在这里
    const cur = this.data.currentTab
    //没有有缓存，切换Tab请求数据
    if (
      (this.data.cur === 0 && this.data.currentTabList.indexOf(cur) === -1) ||
      (this.data.cur === 1 && this.data.currentTabList1.indexOf(cur) === -1)
    ) {
      this.onReset()
    }
  },
  async onReset(isLoadMore = false) {
    if (isLoadMore) {
      wx.showLoading({
        title: '加载中',
      })
    }
    this.data.cur === 0 ? this.getHottopic(isLoadMore) : this.getNewesttopic(isLoadMore)
    wx.hideLoading()
  },
  async onPullDownRefresh() {
    await this.onReset()
    wx.stopPullDownRefresh()
  },
  onReachBottom() {
    if (
      (this.data.cur === 0 && this.data.navData[this.data.currentTab].isLastPage) ||
      (this.data.cur === 1 && this.data.navData1[this.data.currentTab].isLastPage)
    )
      wx.showToast({ title: '已没有更多', icon: 'none', duration: 1000 })
    this.onReset(true)
  },
  /** 最新圈子 */
  async getNewesttopic(isLoadMore: boolean) {
    const categoryId = this.data.currentTab
    let list = await topicApi.getUserTopics({
      topic_category_id: this.data.navData1[categoryId].id,
      index:
        isLoadMore && this.data.list1[categoryId]
          ? this.data.list1[categoryId][this.data.list1[categoryId].length - 1].id
          : 0,
      limit: 18,
      status: 'passed',
    })
    const isLastPage = list.length < 18
    const currentTabList1 = this.data.currentTabList1
    currentTabList1.push(this.data.currentTab)
    list =
      isLoadMore && this.data.list1[categoryId] ? [...this.data.list1[categoryId], ...list] : list
    this.setData({
      [`list1[${categoryId}]`]: list,
      [`navData1[${categoryId}].isLastPage`]: isLastPage,
      currentTabList1,
      [`navData1[${categoryId}].show`]: list.length === 0,
    })
  },
  /** 热门圈子 */
  async getHottopic(isLoadMore: boolean) {
    const categoryId = +this.data.currentTab
    let list =
      categoryId === 0
        ? await topicApi.getHotTopicsRecommend({
          offset:
            isLoadMore && this.data.list[categoryId] ? this.data.list[categoryId].length : 0,
          limit: 18,
        })
        : await topicApi.getHotTopics({
          topic_category_id: this.data.navData1[categoryId].id,
          offset:
            isLoadMore && this.data.list[categoryId] ? this.data.list[categoryId].length : 0,
          limit: 18,
          status: 'passed',
        })
    const isLastPage = list.length < 18
    const currentTabList = this.data.currentTabList
    currentTabList.push(this.data.currentTab)
    list =
      isLoadMore && this.data.list[categoryId] ? [...this.data.list[categoryId], ...list] : list
    this.setData({
      [`list[${categoryId}]`]: list,
      [`navData[${categoryId}].isLastPage`]: isLastPage,
      currentTabList,
      [`navData[${categoryId}].show`]: list.length === 0,
    })
  },
  /** 缓存改变状态 */
  changeTopic(topic: DomoTopic) {
    const topics = this.data.list[this.data.currentTab] || []
    const topics1 = this.data.list1[this.data.currentTab] || []
    topics[topics.findIndex((i: any) => i.id === topic.id)] = topic
    topics1[topics1.findIndex((i: any) => i.id === topic.id)] = topic
    this.setData({
      [`list[${this.data.currentTab}]`]: topics,
      [`list1[${this.data.currentTab}]`]: topics1,
    })
  },
  /** 删除圈子时改变缓存 */
  deleteTopic(topic: DomoTopic) {
    const topics = this.data.list[this.data.currentTab] || []
    const topics1 = this.data.list1[this.data.currentTab] || []
    topics.splice(
      topics.findIndex((i: any) => i.id === topic.id),
      1,
    )
    topics1.splice(
      topics1.findIndex((i: any) => i.id === topic.id),
      1,
    )
    this.setData({
      [`list[${this.data.currentTab}]`]: topics,
      [`list1[${this.data.currentTab}]`]: topics1,
    })
  },
  /** 判断是否拥有创建圈子的权限 */
  async resolveCreateTopic() {
    // const {
    //   data: { user },
    // } = this
    // topicApi.getTopicConfig().then((data: TopicConfig) => {
    //   const {
    //     config: { create_permission, permission },
    //   } = data
    //   const abilities: any = GlobalData.userAbilities
    //   this.setData({
    //     create_permission,
    //     canCreate:
    //       create_permission === 'all'
    //         ? true
    //         : create_permission === 'verification' &&
    //           user &&
    //           user.verification &&
    //           user.verification.state === 1
    //         ? true
    //         : create_permission === 'specialUser' &&
    //           abilities &&
    //           abilities.some((v: any) => v.name === permission)
    //         ? true
    //         : false,
    //   })
    // })
    const { visible, hidden } = await topicApi.canCreatTopic()
    this.setData({ visible, hidden })
  },
  /** 创建圈子 */
  creatTopic() {
    const {
      data: { visible, hidden },
    } = this
    if (!visible && !hidden) {
      wx.showToast({
        title: '您没有创建圈子的权限',
        icon: 'none',
      })
      return
    }
    wx.navigateTo({
      url: `/mine/create-topic/create-topic`,
    })
  },
})
